package com.github.springbootPlus.config.utils;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;

import java.io.IOException;

/**
 * @className: ResourceUtils
 * @description:
 * @author: WANGHUI
 * @createDate: 2018/5/10 12:09
 * @version: 1.0
 */
public class ResourceUtils extends org.springframework.util.ResourceUtils {

    static ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(null);

    public static Resource getResource(String location) {
        Resource resource = getResourceFromClassPath(location);
        if (!resource.exists()) {
            resource = getResourceFromJar(location);
        }
        return resource;
    }

    public static Resource[] getResources(String location) {
        Resource[] resources = getResourcesFromClassPath(location);
        if (resources == null || resources.length == 0) {
            resources = getResourcesFromJar(location);
        }
        return resources;
    }

    public static Resource getResourceFromJar(String location) {

        return resolver.getResource(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + location);
    }


    public static Resource[] getResourcesFromJar(String location) {
        try {
            return resolver.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + location);
        } catch (IOException e) {
            return null;
        }
    }

    public static Resource getResourceFromClassPath(String location) {
        return resolver.getResource(ResourceUtils.CLASSPATH_URL_PREFIX + location);
    }


    public static Resource[] getResourcesFromClassPath(String location) {
        try {
            return resolver.getResources(ResourceUtils.CLASSPATH_URL_PREFIX + location);
        } catch (IOException e) {
            return null;
        }
    }
}
